﻿using System;
using System.Drawing.Imaging;
using System.IO;

namespace PdfWizard.UI.Services
{
    public class CompressionService : ICompressionService
    {
		#region Static Methods (1)
		private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }
		#endregion

		#region Methods (2)

        /// <summary>
        /// Compresses the image.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="compressionFactor">The compression factor.</param>
        /// <returns></returns>
		public System.Drawing.Image CompressImage(Stream stream, int compressionFactor)
        {
            return CompressImage(System.Drawing.Image.FromStream(stream), compressionFactor);
        }

		/// <summary>
        /// Compresses the image.
        /// </summary>
        /// <param name="originalImage">The original image.</param>
        /// <param name="compressionFactor">The compression factor.</param>
        /// <returns></returns>
        public System.Drawing.Image CompressImage(System.Drawing.Image originalImage, int compressionFactor)
        {
            MemoryStream compressedImageStream = new MemoryStream();

            if (compressionFactor < 0 || compressionFactor > 100)
                throw new ArgumentOutOfRangeException("compressionFactor must be between 0 and 100.");

            EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, compressionFactor); 
            ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;

            originalImage.Save(compressedImageStream, jpegCodec, encoderParams);
            return System.Drawing.Image.FromStream(compressedImageStream, true, true);

        }

		#endregion
    }
}
